from app import CONST
from app.Models.RedPackRecord import RedPackRecord
from app.Models.RedPackage import RedPackage
from app.Vendor import Utils
from app.Vendor.Decorator import transaction
import random, time

class RedPackageService():
    
    # 领取逻辑
    @staticmethod
    @transaction
    def draw(params, user_info):
        #先查询红包余额是否足够
        redPackInfo = RedPackage().getOne(RedPackage, {RedPackage.id == params['red_package_id']})
        redPackRecordSumPrice = RedPackRecord().getCount(RedPackRecord, {RedPackRecord.red_package_id == params['red_package_id']}, 'price')
        redPackRecordCount = RedPackRecord().getCount(RedPackRecord, {RedPackRecord.red_package_id == params['red_package_id']})
        redPackRecordSumPrice = redPackRecordSumPrice if redPackRecordSumPrice > 0  else 0
        price = 0
        if redPackInfo['number'] -1 == redPackRecordCount:
            price = redPackInfo['price'] - redPackRecordSumPrice
            #领取并入库
            RedPackRecord().add(RedPackRecord, {
                'red_package_id': params['red_package_id'],
                'price':price,
                'status': CONST['REDPACKRECORDTATUS']['NORMAL']['value'],
                'create_time': int(time.time()),
                'update_time': int(time.time())
            })
            #更新最佳
            RedPackRecord().updateBestByRedPackId( params['red_package_id'])
            return Utils.formatBody({'action': "draw"})

        elif redPackInfo['number'] > redPackRecordCount:
            price = round(random.uniform(redPackRecordSumPrice, redPackInfo),2)
            RedPackRecord().add(RedPackRecord, {
                'red_package_id': params['red_package_id'],
                'price':price,
                'status': CONST['REDPACKRECORDTATUS']['NORMAL']['value'],
                'create_time': int(time.time()),
                'update_time': int(time.time())
            })
            #更新最佳
            RedPackRecord().updateBestByRedPackId( params['red_package_id'])
            return Utils.formatBody({'action': "draw"})
        else:
            return Utils.formatError(CONST['CODE']['ERROR']['value'], '余额不足')
        #领取并入库
        #更新最佳
        #返回领取成功
        #不足够返回错误
